package com.vitabuybuy.tv.dialog

import android.app.Dialog
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.util.DisplayMetrics
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ScreenUtils
import com.vitabuybuy.tv.adaptebinding.ImageAdapter
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ItemAttributeBinding
import com.vitabuybuy.tv.dto.GoodsDetailsDto
import com.library.common.base.BindRecycAdapter
import com.library.common.toast.XToast
import com.library.common.util.DensityUtil
import com.vitabuybuy.tv.adaptebinding.TextAdapter
import com.zhy.view.flowlayout.FlowLayout
import com.zhy.view.flowlayout.TagAdapter
import kotlinx.android.synthetic.main.dialog_spec_selector.*
import java.util.regex.Pattern
import kotlin.math.roundToInt

/**
 * 作者：SimGa
 * 日期：2020/12/13
 * 时间：12:53
 * 包名：com.vitabuybuy.tv.dialog
 */
class SpecSelectorDialog(context: Context) : Dialog(context, R.style.Dialog) {

    private val specAdapter by lazy { SpecAdapter() }
    private var valusList: List<GoodsDetailsDto.GoodsListBean>? = null
    private var stock = 0
    private var goodId = -1
    private var groupbuyId = -1
    private var type = TYPE_BY_NOMAR_GOODS

    companion object {
        const val TYPE_BY_NOMAR_GOODS = 1001
        const val TYPE_BY_GROUP_BUY = 1002
        const val TYPE_BY_ONLY_AND_TO_CART = 1003
    }

    init {
        this.setCanceledOnTouchOutside(true)
        setContentView(R.layout.dialog_spec_selector)
        val window = window
        window!!.setGravity(Gravity.BOTTOM) // 此处可以设置dialog显示的位置
        window.setWindowAnimations(R.style.bottom_int_out_dialog_style) // 添加动画
        val dm = DisplayMetrics()
        window.windowManager.defaultDisplay.getMetrics(dm)
        window.setLayout(dm.widthPixels, (ScreenUtils.getScreenHeight() * 3.5 / 5).roundToInt())
        window.setBackgroundDrawable(ColorDrawable(0x00000000))

        rcvAttribute.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = specAdapter
        }
        specAdapter.onItemClick = {
            val ids = ArrayList<Int>()
            if (it.size == specAdapter.mData.size) {
                for (map in it) {
                    for (set in map.value) {
                        ids.add(specAdapter.mData[map.key].valueList[set].id)
                    }
                }
                ids.sort()
                var code = ""
                for (set in ids) {
                    code = "$code${set}-"
                }
                code = Pattern.compile("\\-+$").matcher(code).replaceAll("")
                for (good in valusList!!) {
                    if (code == good.code) {
                        if (good.image != null) {
                            ImageAdapter.setNomalImageUrl(
                                ivImage,
                                good.image,
                                ContextCompat.getDrawable(context, R.drawable.default_image)
                            )
                        }
                        TextAdapter.setNowPrice(
                            tvPrice,
                            if (groupbuyId != -1) good.promotionPrice else good.salePrice
                        )
                        goodId = good.id
                        stock = if (groupbuyId != -1) good.promotionQuantity else good.stocks
                        tvStock.visibility = View.VISIBLE
                        TextAdapter.setStockTextView(tvStock, stock)
                        if(stock == 0) tvQuantity.text = "0" else tvQuantity.text = "1"
                        break
                    }
                }
            }
        }
        ivClose.setOnClickListener { dismiss() }
        ivMinus.setOnClickListener {
            var buyNum = tvQuantity.text.toString().toInt()
            if (buyNum == 1) {
                return@setOnClickListener
            }
            buyNum--
            tvQuantity.text = buyNum.toString()
        }
        ivAdd.setOnClickListener {
            var buyNum = tvQuantity.text.toString().toInt()
            if (buyNum == stock) {
                return@setOnClickListener
            }
            buyNum++
            tvQuantity.text = buyNum.toString()
        }
        btnAddToShoppingCart.setOnClickListener {
            if (goodId == -1) {
                XToast.normal(context.getString(R.string.please_choose_commodity_specification))
                return@setOnClickListener
            }
            if(tvQuantity.text.toString().toInt() == 0){
                XToast.normal(context.getString(R.string.this_goods_stock_is_zreo))
                return@setOnClickListener
            }
            onAddToCartClick(goodId, tvQuantity.text.toString().toInt())
            dismiss()
        }
        btnBuyNow.setOnClickListener {
            if (goodId == -1) {
                XToast.normal(context.getString(R.string.please_choose_commodity_specification))
                return@setOnClickListener
            }
            if(tvQuantity.text.toString().toInt() == 0){
                XToast.normal(context.getString(R.string.this_goods_stock_is_zreo))
                return@setOnClickListener
            }
            when (type) {
                TYPE_BY_NOMAR_GOODS -> {
                    onbuyNowClick(goodId, tvQuantity.text.toString().toInt())
                }
                TYPE_BY_GROUP_BUY -> {
                    onGroupBuyClick(goodId, groupbuyId, tvQuantity.text.toString().toInt())
                }
            }
            dismiss()
        }
    }

    lateinit var onAddToCartClick: (goodId: Int, buyNum: Int) -> Unit
    lateinit var onbuyNowClick: (goodId: Int, buyNum: Int) -> Unit
    lateinit var onGroupBuyClick: (goodId: Int, groupbuyId: Int, buyNum: Int) -> Unit

    fun setBottomBtn(type: Int) {
        this.type = type
        when (type) {
            TYPE_BY_NOMAR_GOODS -> {
                btnAddToShoppingCart.run {
                    visibility = View.VISIBLE
                    text = context.getString(R.string.add_to_shopping_cart)
                }
                btnBuyNow.run {
                    visibility = View.VISIBLE
                    text = context.getString(R.string.buy_now_2)
                }
            }
            TYPE_BY_GROUP_BUY -> {
                btnAddToShoppingCart.run {
                    visibility = View.GONE
                }
                btnBuyNow.run {
                    visibility = View.VISIBLE
                    text = context.getString(R.string.confirm)
                }
            }
            TYPE_BY_ONLY_AND_TO_CART -> {
                btnAddToShoppingCart.run {
                    visibility = View.VISIBLE
                }
                btnBuyNow.run {
                    visibility = View.GONE
                }
            }
        }
    }

    fun groupbuyId(groupbuyId: Int) {
        this.groupbuyId = groupbuyId
    }

    fun setSpecDatas(
        list: List<GoodsDetailsDto.AttributeListBean>,
        valusList: List<GoodsDetailsDto.GoodsListBean>,
        orginPrice: Double,
        image: String
    ) {
        goodId = -1
        specAdapter.setNewData(list)
        this.valusList = valusList
        ImageAdapter.setNomalImageUrl(
            ivImage,
            image,
            ContextCompat.getDrawable(context, R.drawable.default_image)
        )
        TextAdapter.setNowPrice(tvPrice, orginPrice)
    }

    class SpecAdapter :
        BindRecycAdapter<ItemAttributeBinding, GoodsDetailsDto.AttributeListBean>() {
        var selectedMap = HashMap<Int, Set<Int>>()
        override fun onBindViewHolder(
            mBinding: ItemAttributeBinding,
            itemData: GoodsDetailsDto.AttributeListBean,
            holder: RecyclerView.ViewHolder,
            position: Int
        ) {
            mBinding.tvValueName.text = itemData.name
            mBinding.tagLayout.adapter = object :
                TagAdapter<GoodsDetailsDto.AttributeListBean.ValueListBean>(itemData.valueList) {
                override fun getView(
                    parent: FlowLayout,
                    position: Int,
                    str: GoodsDetailsDto.AttributeListBean.ValueListBean
                ): View {
                    val tvTip = LayoutInflater.from(mContext).inflate(
                        R.layout.item_att,
                        mBinding.tagLayout, false
                    ) as TextView
                    tvTip.text = str.text
                    val ll = tvTip.layoutParams as ViewGroup.MarginLayoutParams
                    ll.rightMargin = DensityUtil.dip2px(20f)
                    ll.bottomMargin = DensityUtil.dip2px(20f)
                    tvTip.layoutParams = ll
                    return tvTip
                }
            }
            mBinding.tagLayout.setOnSelectListener {
                if (it.isEmpty()) {
                    selectedMap.remove(position)
                } else {
                    selectedMap[position] = it
                }
                onItemClick(selectedMap)
            }
        }

        override fun normalViewId(viewType: Int): Int {
            return R.layout.item_attribute
        }

        lateinit var onItemClick: (selectedMap: HashMap<Int, Set<Int>>) -> Unit
    }
}